'use strict'

// var Fibers=require('fibers')
// var mysql=require('mysql')
class db_utils {

    constructor() {
        this.mysql = require('mysql');
        this.Fiber = require('fibers');
        this.pool = null;
    }

    init(config) {
        this.pool = this.mysql.createPool({
            host: config.HOST,
            user: config.USER,
            password: config.PSWD,
            database: config.DB,
            port: config.PORT,
        });
    }

    nop(a, b, c, d, e, f, g) {

    }

//读取原生库 usr/local/houtai_crm/node_modules/fibers/bin/linux-x64-48/fibers
    query(sql) {
        var ret = {
            err: null,
            rows: null,
            fields: null,
        };
        var Fibers = this.Fiber;
        var pool = this.pool;
        //线程池注意在使用fibers current 当前必须先有fibers run,否则undefine
        Fibers(function () {
                var fiber = Fibers.current;
                pool.getConnection(function (err, conn) {
                    if (err) {
                        ret.err = err;
                        fiber.run();
                    } else {
                        conn.query(sql, function (qerr, vals, fields) {
                            //释放连接
                            conn.release();
                            ret.err = qerr;
                            ret.rows = vals;
                            ret.fields = fields;
                            fiber.run();
                        });
                    }
                });
                Fibers.yield();
                return ret;
            }
        ).run();
    }
}

module.exports = db_utils;